<!doctype html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-sclae=1.0,user-scalable=0">
	<title>宠物速配，撩解一下</title>
	<script type="text/javascript" src="js/flexible.js"></script>
	<link rel="stylesheet" type="text/css" href="css/base.css">
	<script type="text/javascript" src="../../js/zepto.min.js"></script>
	<script src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
	<script type="text/javascript">
		var tipTimer=null;
		var tip=function(text){
			clearTimeout(tipTimer);
			if($('.tipW').length>0){$('.tipW').remove();}
			var ele=$('<div/>',{class:'tipW'});
			ele.css({'position':'fixed','z-index':'1000','padding':'10px 20px','text-align':'center','font-size':'14px','top':'50%','display':'table','left':'50%','-webkit-transform':'translate(-50%, 0)','transform':'translate(-50%, 0)','background':'rgba(0, 0, 0, .8)','color':'#fff','opacity':'1','border-radius':'8px','max-width':'80%'});
			ele.html(text);
			$('body').append(ele);
			tipTimer=setTimeout(function(){
				ele.animate({'top':'-200px'},function(){
					ele.remove();
				})
			},3000);
		};
		function getPixelRatio(context){
      var backingStore = context.backingStorePixelRatio ||
      	context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio || 1;
      return (window.devicePixelRatio || 1) / backingStore;
    }
    // ip
    var petIp=returnCitySN["cip"];
	</script>
</head>
<body style="background:#FFA66A;">
	<div class="upload">
		<div class="cont">
			<div class="head-img img-gg">
				<div class="imgWrap">
					<img src="img/wenhao.png">
				</div>
				<div class="name name-gg"></div>
			</div>
			<div class="head-img img-mm">
				<div class="imgWrap">
					<img src="img/wenhao.png">
				</div>
				<div class="name name-mm"></div>
			</div>
			<div class="codeW">
				<img src="img/code.png">
			</div>
		</div>
		<div class="tip cen">温馨提示：上传宠物正面照效果更好哦</div>
		<!-- 上传照片 -->
		<div class="box1">
			<div class="sex" flex="main:center cross:center">
				<img src="img/sel.png">
				<div class="btn btn-mm" value="mm"></div>
				<div class="btn btn-gg" value="gg"></div>
			</div>
			<div class="input" flex="main:center cross:center">
				<input type="text" placeholder="填写宠物昵称..." name="petName" maxlength="5" onkeyup="value=value.replace(/[^\u4E00-\u9FA5A-Za-z0-9\s]+$/,'')">
				<div class="btn" id="upload"></div>
				<input type="file" id="file" accept="image/*">
			</div>
		</div>
		<!-- 立即生成 -->
		<div class="box2">
			<div class="input" flex="main:center cross:center">
				<div class="btn" id="back"></div>
				<div class="btn" id="generatePic"></div>
			</div>
		</div>
		<!-- 转发分享 -->
		<div class="box3">
			<ul flex="main:justify">
				<li id="shareFriend">
					<span></span>
					<p>转发好友</p>
				</li>
				<li id="shareCircle">
					<span></span>
					<p>分享朋友圈</p>
				</li>
				<li id="saveImg">
					<span></span>
					<p>保存相册</p>
				</li>
				<li id="resetMake">
					<span></span>
					<p>重新制作</p>
				</li>
			</ul>
		</div>
	</div>
	<!-- 裁切框 -->
	<div class="crop-box">
		<div class="wrap">
			<div class="img">
      	<img id="image" src="">
      </div>
      <div class="button" flex="main:center">
      	<a href="javascript:;" id="cancel">取消</a>
      	<a href="javascript:;" id="confirm">确定</a>
      </div>
		</div>
	</div>
	<!-- 分享提示框 -->
	<div class="sharePop">
		<img src="img/share_tip1.png">
	</div>
	<script type="text/javascript" src="js/cropper.min.js"></script>
	<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
	<script>
		// 根据url参数选择模板
		var url=location.search,template,sexV,shareImg,wname,resData,encodeStr,mt;
		if (url.indexOf("?") != -1) {
			template = url.substr(1).split("&");
			template = template[0].split("=")[1];
			$('.upload').addClass('moban'+template);
			var img=document.createElement('img');
			img.className='img',img.style.width='100%',img.src='./img/cont'+template+'.png';
			$('.cont').prepend(img);
		}
		// 微信接口配置
    $.post(baseUrl+'getSignature',{
			pathname:location.pathname+location.search
		},function(res){
			wx.config({
				debug: false,
			    appId: res.appId,
			    timestamp: res.timestamp,
			    nonceStr: res.nonceStr,
			    signature: res.signature,
			    jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline']
			});
		})
		// 匹配另一半头像素材
		var matchList={
			mm:[
				{img:'img/match_mm1.png',name:'picky'},
				{img:'img/match_mm2.png',name:'snow'},
				{img:'img/match_mm3.png',name:'白糖'},
				{img:'img/match_mm4.png',name:'包包'},
				{img:'img/match_mm5.png',name:'葱饼'},
				{img:'img/match_mm6.png',name:'哈尼'},
				{img:'img/match_mm7.png',name:'皮蛋'},
				{img:'img/match_mm8.png',name:'噗噗'},
				{img:'img/match_mm9.png',name:'土豆'},
				{img:'img/match_mm10.png',name:'乌冬'}
			],
			gg:[
				{img:'img/match_gg1.png',name:'duke'},
				{img:'img/match_gg2.png',name:'happy'},
				{img:'img/match_gg3.png',name:'joba'},
				{img:'img/match_gg4.png',name:'包子'},
				{img:'img/match_gg5.png',name:'财宝'},
				{img:'img/match_gg6.png',name:'单身狗'},
				{img:'img/match_gg7.png',name:'哈利'},
				{img:'img/match_gg8.png',name:'老白居'},
				{img:'img/match_gg9.png',name:'妥妥'},
				{img:'img/match_gg10.png',name:'小七'}
			]
		},
		// 固定名字内容
		nameDefault=[
			{gg:'·寺',mm:'·菜'},
			{gg:'·牛郎',mm:'·织女'},
			{gg:'',mm:''},
			{gg:'杨·',mm:'·龙女'}
		];
		// 随机选张头像匹配
		var rand=Math.floor(Math.random(0,1)*9),arr=matchList['mm'][rand],arr2=matchList['gg'][rand];
		// 选择性别
		$('.sex .btn').click(function(){
			$(this).addClass('active').siblings().removeClass('active');
		})
		// 点击上传
		$('#upload').click(function(){
			if($('.sex .btn.active').length==0){
				tip('请先填写性别及昵称');
				return;
			}
			if($(".input input[name=petName]").val().trim()==''){
				tip('请先填写性别及昵称');
				return;
			}
			$('#file').click();
		})
		// 裁切开始
		var cropper,image=document.querySelector('#image');
		$('#file').change(function(e){
			var files=e.target.files,file;
			var done = function (url) {
      	e.target.value = '';
      	image.src = url;
      	$('.tip').html('可移动/放大头像，以调整最佳位置哦');
        	$('.crop-box').show();
      	cropper=new Cropper(image,{
					dragMode: 'move',
	        viewMode: 3,
	        restore: false,
	        guides: false,
	        center: false,
	        highlight: false,
	        minCropBoxWidth:300,
	        minCropBoxHeight:300,
	        cropBoxMovable:false,
	        cropBoxResizable: false,
	        toggleDragModeOnDblclick: false,
				});
	    };
      if (files && files.length > 0) {
        	file = files[0];
        	if (URL) {
            done(URL.createObjectURL(file));
        } else if (FileReader) {
            reader = new FileReader();
            reader.onload = function (e) {
              done(reader.result);
            };
            reader.readAsDataURL(file);
        }
      }
		})
    //取消裁切回调
    function hideCall(){
			cropper.destroy();
	    $('.crop-box').hide();
		}
		// 确定裁切
		$('#confirm').click(function(){
			var canvas = cropper.getCroppedCanvas({
				maxWidth:200
			});
			sexV=$('.sex .btn.active').attr('value');
      $('.img-'+sexV+' img').attr({'src':canvas.toDataURL('image/jpeg',0.92),'style':''});
      $('.img-'+sexV).find('.name-'+sexV).text($(".input input[name=petName]").val())
      if(template==4){
      	sexV=='gg'&&$('.name-gg').text(nameDefault[template-1].gg+$(".input input[name=petName]").val())||$('.name-mm').text($(".input input[name=petName]").val()+nameDefault[template-1].mm)
      }else{
      	$('.name-'+sexV).text($(".input input[name=petName]").val()+nameDefault[template-1][sexV])
      }
      // 模板2的gg名字过长宽度调整
    	if(template==2&&$(".name-gg").text().length==8){
				$(".name-gg").css('left','0.9rem');
			}
      $('.box1').hide(),$('.box2').show();
      hideCall();
			// 移动头像，缩放头像
			window.requestAnimFrame = function () {
			    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || function (callback) {
			        window.setTimeout(callback, 1000 / 60);
			    };
			}();
			function set($el, transform) {
			    window.requestAnimFrame(function () {
			        var wid=$el.parent().width()*transform.scale;
			        $el.css({'left':transform.x+'px','top':transform.y+'px',width:wid});
			    });
			}
			function limit(wrap, el, trans) {
		    var bounce = el.offsetWidth/2;
		    var minX = -bounce;
		    var maxX = bounce;
		    var minY = -bounce;
		    var maxY = bounce;
		    trans.x = trans.x < minX ? minX : trans.x;
		    trans.x = trans.x > maxX ? maxX : trans.x;
		    trans.y = trans.y < minY ? minY : trans.y;
		    trans.y = trans.y > maxY ? maxY : trans.y;
		    return trans;
			}
      // drag;
      var trans = {
		    x: 0,
		    y: 0,
		    scale: 1,
		    rotate: 0
			};
			var $drag = $pinch=$('.img-'+sexV+' img');
			var wrap = document.querySelector('.cont');
			var wrapRect = wrap.getBoundingClientRect();
			var elRect = $drag[0].getBoundingClientRect();
			var freeze = false;
			mt = MTouch('.cont');
			mt.on('drag', function (ev) {
		    if (!freeze) {
	        trans.x += ev.delta.deltaX;
	        trans.y += ev.delta.deltaY;
	        set($drag, limit(wrap, $drag[0], trans));
		    }
			});
			// pinch;
			mt.on('pinch', function (ev) {
		    trans.scale *= ev.delta.scale;
		    set($pinch, limit(wrap, $pinch[0], trans));
			});
		})
		// 取消裁切
		$('#cancel').click(function(){
			hideCall();
		})
		// 返回上一步
		$('#back').click(function(){
			$('.box1').show(),$('.box2').hide();
			$('.img-'+sexV+' img').attr({'src':'img/wenhao.png','style':''});
			$('.sex .btn').removeClass('active');
			$('.input input').val('');
			$('.name-'+sexV).text('');
			mt.destroy();
		})
    // 生成图片
    $('#generatePic').on('touchstart',function(){
    	$('.codeW').show();
    	$('.tip').css('opacity','0');
    	// 自动匹配头像
      if(sexV=='mm'){
      	$('.cont .img-gg img').attr('src',arr2.img);
      	if(template==4){
      		$('.cont .img-gg .name').text(nameDefault[template-1].gg+arr2.name);
        }else{
        	$('.cont .img-gg .name').text(arr2.name+nameDefault[template-1].gg);
        }
      }else{
      	$('.cont .img-mm img').attr('src',arr.img);
      	$('.cont .img-mm .name').text(arr.name+nameDefault[template-1].mm)
      }
      // 传参到分享页面
    	wname=$('.img-'+sexV+' .name').text();
    	// 头像匹配完成
    	if($('.img-'+sexV+' img').attr('src')!='img/wenhao.png'){
    		// 配置canvas
      	var shareContent = $('.cont')[0],// 需要绘制的部分的 (原生）dom 对象 
          width = shareContent.offsetWidth,  // 获取(原生）dom 宽度
          height = shareContent.offsetHeight, // 获取(原生）dom 高
          offsetTop = shareContent.offsetTop,  //元素距离顶部的偏移量
          canvas = document.createElement('canvas'),  //创建canvas 对象
          context = canvas.getContext('2d'),
          scaleBy = getPixelRatio(context);  //获取像素密度的方法 (也可以采用自定义缩放比例)
        canvas.width = width * scaleBy,   //这里 由于绘制的dom 为固定宽度，居中，所以没有偏移
        canvas.height = (height + offsetTop) * scaleBy,  // 注意高度问题，由于顶部有个距离所以要加上顶部的距离，解决图像高度偏移问题
        context.scale(scaleBy, scaleBy);
        var opts = {
        	backgroundColor:null,
          allowTaint:true,//允许加载跨域的图片
          tainttest:true, //检测每张图片都已经加载完成
          scale:scaleBy, // 添加的scale 参数
          canvas:canvas, //自定义 canvas
          logging: false, //日志开关，发布的时候记得改成false
          width:width, //dom 原始宽度
          height:height //dom 原始高度
        };
        // 生成带二维码的图
      	setTimeout(function(){
      		html2canvas(shareContent,opts).then(function (canvas) {
            var dataUrl = canvas.toDataURL('image/png'),img=document.createElement('img');
            shareImg=canvas.toDataURL('image/jpeg',0.8);
            img.src=dataUrl,img.style.cssText='width:100%;position:absolute;left:0;top:0;z-index:999;';
            $('.cont').append(img);
            // 提交图片流
	        	$.post(baseUrl+'fileUpload',{
		    			base64String:shareImg,
		    			wname:wname
		    		},function(res){
		    			resData=res.data;
		    			encodeStr=encodeURIComponent('&sharePara='+resData);
		    			// 分享好友设置
			        wx.onMenuShareAppMessage({
		            title: '今天，我的爱宠终于脱单了！没想到对象竟是TA…',
		            desc: ' ',
		            link: baseUrl+'share.html?moban='+template+encodeStr,
		            imgUrl: 'https://applet.petpethouse.com/uaf-pet-monitor/img/ic.png',
		            success: function (res) {
		            	// 统计转发好友次数
			        		$.post(baseUrl+'addMonitor',{event:'4'})
		            }
			        });
		    			// 分享朋友圈设置
			        wx.onMenuShareTimeline({
		            title: '今天，我的爱宠终于脱单了！没想到对象竟是TA…',
		            link: baseUrl+'share.html?moban='+template+encodeStr,
		            imgUrl: 'https://applet.petpethouse.com/uaf-pet-monitor/img/ic.png',
		            success: function (res) {
									setTimeout(function(){
										// 统计转发朋友圈次数
						        $.post(baseUrl+'addMonitor',{event:'5'})
									},500);
			          }
			        });
	    			})
	        })
	        $('.box2').hide(),$('.box3').show();
        	// 统计生成的海报数量
	        // $.post(baseUrl+'addMonitor',{event:'3-'+template});
      	},300)
    	}
    })
    // 转发好友
    $('#shareFriend').click(function(){
    	// 显示分享提示框
    	$('.sharePop img').attr('src','img/share_tip1.png');
    	$('.sharePop').show();
    })
    // 转发朋友圈
    $('#shareCircle').click(function(){
    	// 显示分享提示框
    	$('.sharePop img').attr('src','img/share_tip2.png');
    	$('.sharePop').show();
    })
    // 保存相册
    $('#saveImg').click(function(){
    	tip('长按海报即可保存');
    })
    // 重新制作
    $('#resetMake').click(function(){
    	location.href="./upload.html";
    })
    // 点击隐藏分享提示框
    $('.sharePop').click(function(){
    	$('.sharePop').hide();
    })
	</script>
</body>
</html>